package com.wasion.core.task;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.wasion.core.config.Config;
import com.wasion.core.util.AppUtil;

/**
 * 
 * @ClassName: TaskPool
 * @Description: 任务线程池
 * @author 高意
 * @date 2014年7月23日 下午4:51:03
 * 
 */
public class TaskPool {

	/** The tag. */
	private static String LOG_TAG = Config.LOG_TAG_GLOBOL;

	/** 单例对象 The http pool. */
	private static TaskPool mAbTaskPool = null;

	/** 固定5个线程来执行任务. */
	private static int nThreads = 5;

	/** 线程执行器. */
	private static ExecutorService executorService = null;

	/** 下载完成后的消息句柄. */
	private static Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			TaskItem item = (TaskItem) msg.obj;
			if (item.getListener() instanceof TaskListener) {
				((TaskListListener) item.listener).update((List<?>) item
						.getResult());
			} else if (item.getListener() instanceof TaskObjectListener) {
				((TaskObjectListener) item.listener).update(item.getResult());
			} else {
				item.listener.update();
			}
		}
	};

	/**
	 * 初始化线程池
	 */
	static {
		nThreads = AppUtil.getNumCores();
		mAbTaskPool = new TaskPool(nThreads * 5);
	}

	/**
	 * 构造线程池.
	 * 
	 * @param nThreads
	 *            初始的线程数
	 */
	protected TaskPool(int nThreads) {
		executorService = Executors.newFixedThreadPool(nThreads);
	}

	/**
	 * 单例构造图片下载器.
	 * 
	 * @return single instance of AbHttpPool
	 */
	public static TaskPool getInstance() {
		return mAbTaskPool;
	}

	/**
	 * 执行任务.
	 * 
	 * @param item
	 *            the item
	 */
	public void execute(final TaskItem item) {
		executorService.submit(new Runnable() {
			public void run() {
				try {
					// 定义了回调
					if (item.listener != null) {
						item.listener.get();
						// 交由UI线程处理
						Message msg = handler.obtainMessage();
						msg.obj = item;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}

	/**
	 * 
	 * 描述：获取线程池的执行器
	 * 
	 * @return executorService
	 * @throws
	 */
	public static ExecutorService getExecutorService() {
		return executorService;
	}

	/**
	 * 描述：立即关闭.
	 */
	public void shutdownNow() {
		if (!executorService.isTerminated()) {
			executorService.shutdownNow();
			listenShutdown();
		}

	}

	/**
	 * 描述：平滑关闭.
	 */
	public void shutdown() {
		if (!executorService.isTerminated()) {
			executorService.shutdown();
			listenShutdown();
		}
	}

	/**
	 * 描述：关闭监听.
	 */
	public void listenShutdown() {
		try {
			while (!executorService.awaitTermination(1, TimeUnit.MILLISECONDS)) {
				Log.d(LOG_TAG, "线程池未关闭");
			}
			Log.d(LOG_TAG, "线程池已关闭");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
